//
//  IMFowardGroupListVc.m
//  wanzhaoIM
//
//  Created by wanzhao on 15/7/30.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "IMFowardGroupListVc.h"

#import "SettingNormalCell.h"
#import "MicroDef.h"
#import "GroupDetailVC.h"
#import "CGroupModel.h"
#import "CGroupMgr.h"
#import "GroupMenberCell.h"
#import "CHChatRoomBase.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "CDepartmentMgr.h"
#import "CDepartmentModel.h"
#import "UIImageView+WebCache.h"
#import "NSArray+PinYin.h"
#import "CXmppRequestMgr.h"
#import "GroupMemberDetailVC.h"
#import "JKAlertDialog.h"
#import "ChildHoodService.h"
#import "CFolderMgr.h"
#import "CMessageMgr.h"
#import "CMessageModel.h"
#import "UIBarButtonItem+category.h"

#define KSECTIONHEIGHT 35.0f
#define KNORMALCELLHEIGHT 60.0f
@interface IMFowardGroupListVc ()<UITableViewDelegate, UITableViewDataSource>
{
    UITableView *_tableView;
}

@property (nonatomic, strong) NSMutableArray *groupArray;
@property (nonatomic, strong) NSMutableArray *mineGroupArray;
@property (nonatomic, strong) NSMutableArray *otherGroupArray;
@property (nonatomic, strong) CContactModel *curContact;

@end

@implementation IMFowardGroupListVc

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
        // Do any additional setup after loading the view.
    
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitleCenter:@"群"];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"取消" target:self sel:@selector(cancel) titleFont:Font18 titleColor:WhiteColor];

    _tableView = [[UITableView alloc] init];
    _tableView.frame = self.view.frame;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.sectionIndexBackgroundColor = ClearColor;
    _tableView.sectionIndexTrackingBackgroundColor = ClearColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    
    //加载群组数据
    CAccountModel *model = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    self.curContact = [[[CContactMgr alloc] init] loadContactWithUserCode:model.userName];
    
    NSArray *array = [[[CGroupMgr alloc] init] loadAllGroup];
    if (array.count > 0) {
        NSArray *sortArray = [NSArray sortArray:array];
        
        for (CGroupModel *group in sortArray) {
            if ([group.OwnerId isEqualToString:self.curContact.UserID]) {
                [self.mineGroupArray addObject:group];
            } else {
                [self.otherGroupArray addObject:group];
            }
        }
    }

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     _tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, HARDWARE_SCREEN_HEIGHT - 64);
}

- (void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (NSMutableArray *)groupArray
{
    if (_groupArray == nil) {
        _groupArray = [NSMutableArray array];
    }
    return _groupArray;
}


- (NSMutableArray *)mineGroupArray
{
    if (_mineGroupArray == nil) {
        _mineGroupArray = [NSMutableArray array];
    }
    return _mineGroupArray;
}
- (NSMutableArray *)otherGroupArray
{
    if (_otherGroupArray == nil) {
        _otherGroupArray = [NSMutableArray array];
    }
    return _otherGroupArray;
}

- (void)createNewGroup
{
    
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (section == 0) {
        if (self.mineGroupArray.count > 0) {
            return self.mineGroupArray.count;
        } else {
            return self.otherGroupArray.count;
        }
    } else if (section == 1) {
        return self.otherGroupArray.count;
    } else {
        return 0;
    }

    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
    NSInteger section = 0;
    if (self.mineGroupArray.count > 0) {
        section ++;
    }
    if (self.otherGroupArray.count > 0) {
        section ++;
    }
    return section;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CGroupModel *groupModel = nil;
    if (indexPath.section == 0) {
        if (self.mineGroupArray.count > 0) {
            groupModel = self.mineGroupArray[indexPath.row];
        } else {
            groupModel = self.otherGroupArray[indexPath.row];
        }
    } else {
        groupModel = self.otherGroupArray[indexPath.row];
    }

        static NSString *NormalCellIdentifier = @"SettingNormalCell";
        UITableViewCell *cell = nil;
        SettingNormalCell *normalCell = [tableView dequeueReusableCellWithIdentifier:NormalCellIdentifier];
        if (normalCell == nil) {
            normalCell = [[[NSBundle mainBundle] loadNibNamed:@"SettingNormalCell" owner:self options:nil] objectAtIndex:0];
        }
        
        [normalCell.icon setImage:[UIImage imageNamed:[self iconName:indexPath]] forState:UIControlStateNormal];
        normalCell.icon.layer.cornerRadius = 5.0f/2;
        normalCell.icon.layer.masksToBounds = YES;
        [normalCell.titleLabel setText:[NSString stringWithFormat:@"%@(%zd)",groupModel.GroupName,groupModel.UserNum]];
        [normalCell.seperatorLine setHidden:NO];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell = normalCell;
        return cell;
}


-(NSString *)iconName:(NSIndexPath *)indexPath
{
    NSString *iconName = nil;
    
    iconName = @"icon-Group";
    return iconName;
}



#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return KSECTIONHEIGHT;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    //    CGFloat height = 0;
    //    switch (section) {
    //        case 0:
    //            height = 0.01f;
    //            break;
    //        default:
    //            break;
    //    }
    return 0.01f;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    
    UIView *headerView = nil;
    //    if(section == 0)
    //    {
    //        return headerView;
    //    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, KSECTIONHEIGHT);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    
    UIView *endLine = [[UIView alloc] init];
    endLine.frame = CGRectMake(0, KSECTIONHEIGHT-0.5, tableView.frame.size.width, 0.5);
    [endLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:endLine];
    
    UILabel *label = [[UILabel alloc] init];

    if (section == 0) {
        if (self.mineGroupArray.count > 0) {
            [label setText:[NSString stringWithFormat:@"我创建的群(%zd)",self.mineGroupArray.count]];
        } else {
            [label setText:[NSString stringWithFormat:@"我加入的群(%zd)",self.otherGroupArray.count]];
        }
    } else {
        [label setText:[NSString stringWithFormat:@"我加入的群(%zd)",self.otherGroupArray.count]];
    }

    
    [label setTextColor:RGBCOLOR(0x92, 0x92, 0x92)];
    label.frame = CGRectMake(15, 1, 200, KSECTIONHEIGHT-2);
    [headerView addSubview:label];
    
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView *headerView = nil;
    if(section != 1)
    {
        return headerView;
    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 2);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    return headerView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = KNORMALCELLHEIGHT;
    
    if(indexPath.row == 0 && indexPath.section == 0)
    {
        height = KNORMALCELLHEIGHT;
    }
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CGroupModel *model = nil;
    if (indexPath.section == 0) {
        if (self.mineGroupArray.count > 0) {
            model = self.mineGroupArray[indexPath.row];
        } else {
            model = self.otherGroupArray[indexPath.row];
        }
    } else {
        model = self.otherGroupArray[indexPath.row];
    }

        if (model) {
            CContactModel *currentUser = [[[CContactMgr alloc] init] loadContactWithUserId:[[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount].userId];
            //bug 6086 fixed by 荣则兵
            JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"确定发送给:" message:[NSString stringWithFormat:@"%@(%zd)",model.GroupName,model.UserNum]];
            [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
                [self fowardWithGroup:model withCurUser:currentUser];
                
            }];
            
            [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
                
            }];
            [alert show];

        
        } else {
            
        }
}

-(void)fowardWithGroup:(CGroupModel *)group withCurUser:(CContactModel *)currentUser
{
    
    [self dismissViewControllerAnimated:NO completion:^{
        
    }];
    CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
    chat.group = group;
    chat.member = nil;
    
    UINavigationController *rotNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *vc = rotNav.childViewControllers[1];
    [rotNav popToViewController:vc animated:NO];
    
    [rotNav pushViewController:chat animated:YES];
    if ([ChildHoodService defaultService].forwardText !=nil) {
        [[CXmppRequestMgr shareInstance] sendMessageWithMessage:[ChildHoodService defaultService].forwardText messageId:nil curUser:currentUser member:nil group:group];
    }
    if ([ChildHoodService defaultService].fileModel == nil && [ChildHoodService defaultService].imgLocalFilePath.length > 0) {
        UIImage *image = [UIImage imageWithContentsOfFile:[ChildHoodService defaultService].imgLocalFilePath];
        [[CXmppRequestMgr shareInstance] sendImageMessage:image messageId:nil index:0 curUser:currentUser member:nil group:group fileName:nil];
        //            [self cancel];
    } else {
        [[CXmppRequestMgr shareInstance] sendFile:[ChildHoodService defaultService].fileModel messageId:nil curUser:currentUser member:nil group:group];
        //            [self cancel];
    }

}



@end
